#!/usr/bin/env bash
set -e

source $SNAP/actions/common/utils.sh
use_snap_env

exit_if_service_not_expected_to_start flanneld

# Allow some slack for containerd and etcd to start
# so we avoid this edge case: https://forum.snapcraft.io/t/restarting-services-from-configure-hook-race-condition/2513/13
sleep 5

n=0
until [ $n -ge 10 ]
do
  test -e "$SNAP_DATA/args/flannel-network-mgr-config" && test -e "$SNAP_DATA/args/flanneld" && break
  echo "Waiting for flannled configuration to appear. (attempt $n)"
  n=$[$n+1]
  sleep 2
done

# TODO rewrite for snaps
etcd_endpoints="$(cat $SNAP_DATA/args/flanneld | grep "etcd-endpoints" | tr "=" " "| awk '{print $2}')"
cert_file="$(cat $SNAP_DATA/args/flanneld | grep "etcd-certfile" | tr "=" " "| awk '{print $2}')"
cert_file="$(eval echo $cert_file)"
key_file="$(cat $SNAP_DATA/args/flanneld | grep "etcd-keyfile" | tr "=" " "| awk '{print $2}')"
key_file="$(eval echo $key_file)"
ca_file="$(cat $SNAP_DATA/args/flanneld | grep "etcd-cafile" | tr "=" " "| awk '{print $2}')"
ca_file="$(eval echo $ca_file)"
export ETCDCTL_API=3

# TODO get this from a file
data="$(cat $SNAP_DATA/args/flannel-network-mgr-config)"

# Prepare etcd configuration for flannel, iff an etcd endpoint is set.
# Skip this part if an alternate data store is used (e.g. Kubernetes).
if [ ! -z "$etcd_endpoints" ]; then
  if ! "${SNAP}/etcdctl" --endpoints "${etcd_endpoints}" --cert "${cert_file}" --key "${key_file}" --cacert "${ca_file}" del "/coreos.com/network/config"; then
    echo "/coreos.com/network/config is not in etcd. Probably a first time run."
  fi
  "${SNAP}/etcdctl" --endpoints "${etcd_endpoints}" --cert "${cert_file}" --key "${key_file}" --cacert "${ca_file}" put "/coreos.com/network/config" "$data"
fi

set -a
if [ -e "${SNAP_DATA}/args/flanneld-env" ]
then
  . "${SNAP_DATA}/args/flanneld-env"
fi
set +a

# This is really the only way I could find to get the args passed in correctly.
declare -a args="($(cat $SNAP_DATA/args/flanneld))"
exec "$SNAP_DATA/opt/cni/bin/flanneld" "${args[@]}"
